package com.base.cn.platform.os.service.order.order;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.*;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.dao.order.order.OrderDao;
import com.base.cn.platform.os.entity.op.activity.OpActivity;
import com.base.cn.platform.os.entity.op.coupon.OpCoupon;
import com.base.cn.platform.os.entity.op.coupon.OpCouponCode;
import com.base.cn.platform.os.entity.order.PayCallbackEntity;
import com.base.cn.platform.os.entity.order.count.OrderDayNum;
import com.base.cn.platform.os.entity.order.count.OrderFormCountNum;
import com.base.cn.platform.os.entity.order.count.OrderPayTypeCountNum;
import com.base.cn.platform.os.entity.order.count.OrderPriceCountNum;
import com.base.cn.platform.os.entity.order.order.*;
import com.base.cn.platform.os.entity.order.shop.ShopData;
import com.base.cn.platform.os.entity.statistics.base.ZStatisticsOrderBaseCount;
import com.base.cn.platform.os.entity.statistics.trade.PayOrderFormNum;
import com.base.cn.platform.os.entity.statistics.trade.PayTypeCountNum;
import com.base.cn.platform.os.entity.statistics.users.ZStatisticsPayUserCount;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.qa.qaattend.QaAttendService;
import com.base.cn.platform.os.service.exam.record.ExamBuyRecordService;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.base.cn.platform.os.service.op.activity.OpActivityBiz;
import com.base.cn.platform.os.service.op.coupon.OpCouponCodeBiz;
import com.base.cn.platform.os.service.op.coupon.OpCouponShopBiz;
import com.base.cn.platform.os.service.order.callback.RefundCallbackHandle;
import com.base.cn.platform.os.service.order.callback.SuccessCallbackHandle;
import com.base.cn.platform.os.service.order.check.CreateOrderDataFrom;
import com.base.cn.platform.os.service.order.check.OrderCheckHandle;
import com.base.cn.platform.os.service.order.init.ShopDataInit;
import com.base.cn.platform.os.service.order.price.OrderPrice;
import com.base.cn.platform.os.service.order.price.OrderPriceHandle;
import com.base.cn.platform.os.service.user.member.CusUserMemberBuyRecordBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Biz
 *
 * @author s.li
 * @create 2018-05-07-17:20
 */
@Service
public class OrderBiz extends BaseBiz<Order,OrderDao> {

    @Autowired
    private OrderDetailsBiz orderDetailsBiz;
    @Autowired
    private OrderBookBiz orderBookBiz;
    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private SuccessCallbackHandle successCallbackHandle;
    @Autowired
    private RefundCallbackHandle refundCallbackHandle;
    @Autowired
    private OpCouponCodeBiz opCouponCodeBiz;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ShopCartBiz shopCartBiz;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private OpActivityBiz opActivityBiz;
    @Autowired
    private SysConfigBiz sysConfigBiz;
    @Autowired
    private ShopDataInit shopDataInit;
    @Autowired
    private ExamBuyRecordService examBuyRecordService;
    @Autowired
    private OpCouponShopBiz opCouponShopBiz;
    @Autowired
    private CusUserMemberBuyRecordBiz cusUserMemberBuyRecordBiz;
    @Autowired
    private QaAttendService qaAttendService;

    /**
     * 删除订单
     * @param orderIds
     * @param userId
     */
    public void deleteOrder(String orderIds,BigDecimal userId){
        if(StringUtils.isNotEmpty(orderIds) && DataUtil.idIsNotNull(userId)){
            Order order = new Order();
            order.setStatus(2);
            this.updateByWhereSql(order," id in ("+orderIds+") and userId="+userId);
        }
    }

    /**
     * 修改订单状态
     * @param order 订单对象
     * @param sysUserId 管理员ID
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void updateOrderStatus(Order order,BigDecimal sysUserId) throws Exception{
        OrderDetails details = new OrderDetails();
        details.setDetailStatus(order.getOrderStatus());
        details.setPayType(order.getPayType());
        details.setPayTime(order.getPayTime());
        //如果是成功状态
        if(OrderStatus.SUCCESS.equals(order.getOrderStatus())){
            successCallbackHandle.handleSuccess(order,sysUserId);
        }
        //如果是退费
        if(OrderStatus.REFUND.equals(order.getOrderStatus())){
            refundCallbackHandle.refundHandle(order,sysUserId);
        }
        //修改订单
        this.updateByWhereSql(order,null);
        //修改流水
        orderDetailsBiz.updateByWhereSql(details," orderId = "+order.getId());
    }

    /**
     * 获取账户充值订单
     * @return 订单对象
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public Order createAccountOrder(PayCallbackEntity payCallbackEntity) throws Exception{
        Order order = new Order();
        order.setOrderNo(payCallbackEntity.getOrderNo());
        order.setUserId(payCallbackEntity.getUserId());
        order.setOrderType(OrderType.ACCOUNT.getKey());
        order.setPayType(payCallbackEntity.getPayType());
        order.setPayTime(new Date());
        order.setSumPrice(payCallbackEntity.getPrice());
        order.setRealPrice(payCallbackEntity.getPrice());
        order.setOrderStatus(OrderStatus.SUCCESS);
        order.setExternalOrderNo(payCallbackEntity.getExternalOrderNo());
        order.setSellTypeList(","+ShopType.ORDER_SHOP_ACCOUNT+",");
        order.setShopNames("账户充值");
        order.setOrderForm(payCallbackEntity.getOrderForm());
        order.setStatus(1);//状态正常
        this.save(order);
        //创建订单流水
        OrderDetails orderDetails = orderDetailsBiz.saveAccountOrderDetails(order,payCallbackEntity,false,true);
        List<OrderDetails> orderDetailsList = new ArrayList<>();
        orderDetailsList.add(orderDetails);
        order.setOrderDetailsList(orderDetailsList);
        successCallbackHandle.handleSuccess(order);
        return order;
    }

    /**
     * 生成用户登录时的课程订单数据
     * @param user 用户对象
     */
    @Async
    @Transactional
    public void userLoginFreeCourseOrder(CusUser user) throws Exception{
        String courseIds = StringUtils.subHeadTailString(user.getCourseIds(),",");
        BigDecimal userId = user.getId();
        if(DataUtil.idIsNotNull(userId) && StringUtils.isNotEmpty(courseIds)){
            String[] arr = courseIds.split(",");
            if(ObjectUtils.isNotEmpty(arr)){
                Set<String> courseIdSet = new HashSet<>();
                Arrays.stream(arr).forEach(courseId->{
                    if(StringUtils.isNotEmpty(courseId) && StringUtils.isNumber(courseId)){
                        courseIdSet.add(courseId);
                    }
                });
                if(ObjectUtils.isNotEmpty(courseIdSet)){
                    StringBuilder stringBuilder = new StringBuilder();
                    Iterator<String> it = courseIdSet.iterator();
                    int index = 1;
                    while (it.hasNext()){
                        String courseId = it.next();
                        if(index < courseIdSet.size()){
                            stringBuilder.append(courseId).append("-COURSE-1").append(",");
                        }else{
                            stringBuilder.append(courseId).append("-COURSE-1");
                        }
                        index ++;
                    }
                    CreateOrderDataFrom createOrderDataFrom = new CreateOrderDataFrom();
                    createOrderDataFrom.setShopData(stringBuilder.toString());
                    createOrderDataFrom.setUserId(userId);
                    createOrderDataFrom.setAutoGive(true);//设置成系统自动赠送
                    createOrderDataFrom.setPayType(PayType.PAY_TYPE_ADMIN_FREE);
                    createOrderDataFrom.setOrderForm(OrderSource.ORDER_FORM_ADMIN);
                    this.createFreeOrder(createOrderDataFrom);
                }
            }
            user.setCourseIds(" ");
            cusUserBiz.updateById(user,null);
        }
    }

    /**
     * 创建免费订单
     * @param createOrderDataFrom
     * @return Map<String,Object>
     */
    public Map<String,Object> createFreeOrder(CreateOrderDataFrom createOrderDataFrom){
        createOrderDataFrom.setPay(false);
        createOrderDataFrom.setSubmit(true);
        createOrderDataFrom.setFree(true);
        createOrderDataFrom.setOrderType(OrderType.COMMON.getKey());
        //验证订单数据
        Map<String,Object> resultMap = this.checkCreateOrderData(createOrderDataFrom);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        Order order = null;
        try {
            order = this.createOrder(createOrderDataFrom);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.SUCCESS(order);
    }

    /**
     * 验证创建订单的数据
     * @param createOrderDataFrom
     * @return Map<String,Object>
     */
    public Map<String,Object> checkCreateOrderData(CreateOrderDataFrom createOrderDataFrom){
        //初始化工具类、服务接口类
        OrderCheckHandle.courseBuyRecordService = courseBuyRecordService;
        OrderCheckHandle.examBuyRecordService = examBuyRecordService;
        OrderCheckHandle.opCouponCodeBiz = opCouponCodeBiz;
        OrderCheckHandle.opActivityBiz = opActivityBiz;
        OrderCheckHandle.opCouponShopBiz = opCouponShopBiz;
        OrderCheckHandle.cusUserMemberBuyRecordBiz = cusUserMemberBuyRecordBiz;
        OrderCheckHandle.sysConfigBiz = sysConfigBiz;
        OrderCheckHandle.qaAttendService =qaAttendService;

        //初始化商品数据
        shopDataInit.initShopData(createOrderDataFrom);

        //验证订单数据
        Map<String,Object> resultMap = OrderCheckHandle.orderCheck(createOrderDataFrom);
        return resultMap;
    }

    /**
     * 创建免费订单
     * @param userId 用户ID
     * @param shopData 商品数据
     * @return Map<String,Object>
     * @throws Exception
     */
    /*public Map<String,Object> createFreeOrder(BigDecimal userId,String shopData) throws Exception{
        OrderForm orderForm = this.setCreateFreeOrder(userId,shopData, PayType.PAY_TYPE_ADMIN_FREE, OrderSource.ORDER_FORM_ADMIN);
        //检测订单数据
        Map<String,Object> resultMap = this.checkOrderFormData(orderForm);
        if(ObjectUtils.isNotEmpty(resultMap)){
            return resultMap;
        }
        Order order = this.createOrder(orderForm,null,false);
        return ResultUtil.SUCCESS("赠送成功",order);
    }*/

    /**
     * 设置免费赠送订单对象
     * @param userId 用户ID
     * @param shopData 商品数据
     * @param payType 支付类型
     * @param form 订单来源
     * @return OrderForm
     */
    /*public OrderForm setCreateFreeOrder(BigDecimal userId,String shopData,String payType,String form){
        OrderForm orderForm = new OrderForm();
        orderForm.setPay(false);
        orderForm.setUserId(userId);
        orderForm.setOrderType(OrderType.COMMON.getKey());
        orderForm.setShopData(shopData);
        orderForm.setPayType(payType);
        orderForm.setPayTime(new Date());
        orderForm.setOrderForm(form);
        //设置商品数据列表
        orderForm.setShopList(shopBiz.getShopList(orderForm));
        //设置商品名串
        orderForm.setShopNames(shopBiz.getShopNames(orderForm));
        return orderForm;
    }*/

    /**
     * 通过ID，查询订单对象
     * @param condition 查询条件
     * @return Order
     */
    public Order findOrderInfo(OrderCondition condition){
        Order order = this.findById(condition.getId());
        if(ObjectUtils.isNotEmpty(order)){
            order = this.setOrderExData(order,condition.isSetUserData(),condition.isSetDetailsData(),condition.isSetShopData(),condition.isSetOrderBook());
            if(condition.isSetActivity() && DataUtil.idIsNotNull(order.getActivityId())){
                OpActivity activity = opActivityBiz.queryOpActivityById(order.getActivityId(),true,true,false,false);
                order.setActivity(activity);
            }
            if(condition.isSetCoupon() && DataUtil.idIsNotNull(order.getCouponCodeId())){
                OpCouponCode couponCode = opCouponCodeBiz.findCouponCodeById(order.getCouponCodeId(),true);
                order.setCouponCode(couponCode);
            }
            if(ObjectUtils.isNotEmpty(order.getOrderDetailsList())){
                int buyNum = order.getOrderDetailsList().stream().mapToInt(e->e.getBuyNum()).sum();
                order.setBuyNum(buyNum);
            }
        }
        return order;
    }

    /**
     * 通过订单号，查询订单对象
     * @param orderNo 订单号
     * @param setUserData 是否设置用户对象
     * @param setDetailsData 是否设置设置订单流水数据
     * @param setShopData 是否设置流水中的商品数据
     * @param setOrderBook 是否设置订单对象的图书扩展数据
     * @return
     */
    public Order findOrderByOrderNo(String orderNo,
                                    boolean setUserData,
                                    boolean setDetailsData,
                                    boolean setShopData,
                                    boolean setOrderBook){
        Order order = null;
        if(StringUtils.isNotEmpty(orderNo)){
            order = this.findOne("orderNo ='"+orderNo+"'",null);
            if(ObjectUtils.isNotEmpty(order)){
                order = this.setOrderExData(order,setUserData,setDetailsData,setShopData,setOrderBook);
            }
        }
        return order;
    }

    /**
     * 分页查询订单列表
     * @param condition
     * @param page
     * @param setUserData 是否设置用户数据
     * @param setDetailsData 是否设置流水数据
     * @param setShopData 是否设置商品数据(要设置商品数据必须先设置流水数据)
     * @return PageInfo<Order>
     */
    public PageInfo<Order> findOrderPage(OrderCondition condition, Pagination page,
                                         boolean setUserData,
                                         boolean setDetailsData,
                                         boolean setShopData,
                                         boolean setOrderBook){
        condition.setUserIds(orderDetailsBiz.getUsrIds(condition.getKeyword()));
        PageInfo<Order> orderPageInfo = this.findPage(this.getWhereSql(condition),page,null);
        this.setOrderExData(orderPageInfo.getList(),setUserData,setDetailsData,setShopData,setOrderBook);
        return orderPageInfo;
    }

    /**
     * 查询订单列表(不分页)
     * @param condition 查询条件
     * @param setUserData 是否设置用户数据
     * @param setDetailsData 是否设置流水数据
     * @param setShopData 是否设置商品数据(要设置商品数据必须先设置流水数据)
     * @return List<Order>
     */
    public List<Order> findOrderList(OrderCondition condition,
                                     boolean setUserData,
                                     boolean setDetailsData,
                                     boolean setShopData,
                                     boolean setOrderBook){
        condition.setUserIds(orderDetailsBiz.getUsrIds(condition.getKeyword()));
        String whereSql = getWhereSql(condition);
        List<Order> orders = this.find(whereSql, null, null);
        return this.setOrderExData(orders,setUserData,setDetailsData,setShopData,setOrderBook);
    }

    /**
     * 获取当天订单量
     * @param dateTime 时间
     * @return 统计数据对象
     */
    public List<OrderDayNum> queryOrderNowDayNum(String dateTime){
        return orderDao.queryOrderNowDayNum(Order.class,dateTime);
    }

    /**
     * 查询购买课程的用户量
     * @return 用户量
     */
    public Integer queryBuyCourseUserNum(){
        return orderDao.queryBuyCourseUserNum(Order.class);
    }

    /**
     * 查询订单流水总金额
     * @return 订单流水总金额
     */
    public double queryOrderSumPrice(){
        return orderDao.queryOrderSumPrice(Order.class);
    }

    /**
     * 查询统计订单价格区域的数据
     * @return OrderPriceCountNum
     */
    public OrderPriceCountNum queryOrderPriceCountNum(){
        return orderDao.queryOrderPriceCountNum(Order.class);
    }


    /**
     * 查询订单支付方式占比统计数据
     * @return PayTypeCountNum
     */
    public OrderPayTypeCountNum queryOrderPayTypeCountNum(){
        return orderDao.queryOrderPayTypeCountNum(Order.class);
    }

    /**
     * 查询订单的来源数据统计
     * @return OrderFormCountNum
     */
    public OrderFormCountNum queryOrderFormCountNum(){
        return orderDao.queryOrderFormCountNum(Order.class);
    }
    //====================================================================

    /**
     * 设置订单扩展数据
     * @param order 订单对象
     * @param setUserData 是否设置用户对象
     * @param setDetailsData 是否设置设置流水数据
     * @param setShopData 是否设置商品数据
     * @param setOrderBook 是否设置订单的图片扩展数据
     * @return 订单对象
     */
    public Order setOrderExData(Order order,
                                       boolean setUserData,
                                       boolean setDetailsData,
                                       boolean setShopData,
                                       boolean setOrderBook){
        if(ObjectUtils.isNotEmpty(order)){
            this.setOrderExData(Collections.singletonList(order),setUserData,setDetailsData,setShopData,setOrderBook);
        }
        return order;
    }


    /**
     * 获取谋一时间段的订单数据
     * @param map 时间
     * @return 统计数据对象
     */
    public List<Map<String,Object>> queryOrderDayNum(Map<String,Object> map){
        if(StringUtils.isEmpty(map.get("begTime"))&&StringUtils.isEmpty(map.get("endTime"))){
            map.put("begTime",DateUtils.format(new Date(),"yyyy-MM-dd"));
            map.put("endTime",DateUtils.format(new Date(),"yyyy-MM-dd"));
        }
        return orderDao.queryOrderDayNum(Order.class,map);
    }
    /**
     * 设置订单扩展数据
     * @param orderList 订单列表
     * @param setUserData 是否设置用户数据
     * @param setDetailsData 是否设置流水数据
     * @param setShopData 是否设置商品数据
     * @return List<Order>
     */
    private List<Order> setOrderExData(List<Order> orderList,
                                       boolean setUserData,
                                       boolean setDetailsData,
                                       boolean setShopData,
                                       boolean setOrderBook){
        if(setUserData){//设置用户数据
            cusUserBiz.setUserData(orderList,setUserData);
        }
        if(setDetailsData){//设置流水数据
            orderList = this.setDetailsDataOrShopData(orderList,setShopData);
        }
        if(setOrderBook){//设置图书订单扩展数据
            orderList = this.setOrderBook(orderList,setOrderBook);
        }
        return orderList;
    }
    /**
     * 通过ID，查询订单对象
     * @param condition 查询条件
     * @return Order
     */
    public Map<String,List> orderInfoActivity(OrderCondition condition){
      Map <String,List> InfoActivity = new HashMap<>();
        Order order = this.findById(condition.getId());
        if(ObjectUtils.isNotEmpty(order)) {
            if (DataUtil.idIsNotNull(order.getActivityId())) {
                OpActivity opActivity = opActivityBiz.queryOpActivityById(order.getActivityId(), true, true, false, false);
                List<Map<String, Object>> courseTo = opActivity.getCourse();
                List course = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(courseTo)){
                    for(Map courseInfo :courseTo){
                        HashMap<Object, Object> objectMap = new HashMap<>();
                        objectMap.put("name",courseInfo.get("courseName"));
                        course.add(objectMap);
                        objectMap =null;
                    }
                }
                List<OpCoupon> couponTo= opActivity.getCoupons();
                List coupons = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(couponTo)){
                    for(OpCoupon coupon :couponTo){
                        HashMap<Object, Object> objectMap = new HashMap<>();
                        objectMap.put("name",coupon.getTitle());
                        coupons.add(objectMap);
                        objectMap =null;
                    }
                }
                InfoActivity.put("course",course);
                InfoActivity.put("coupon",coupons);
            }

        }
        return InfoActivity;
    }
    /**
     * 设置图书订单扩展数据
     * @param orderList 订单数据列表
     * @param setOrderBook
     * @return List<Order>
     */
    private List<Order> setOrderBook(List<Order> orderList,boolean setOrderBook){
        if(ObjectUtils.isNotEmpty(orderList) && setOrderBook){
            String orderIds = orderList.stream().map(e->e.getId().toString()).distinct().collect(Collectors.joining(","));
            Map<BigDecimal,OrderBook> orderBookMap = orderBookBiz.findOrderBookByOrderIds(orderIds);
            if(ObjectUtils.isNotEmpty(orderBookMap)){
                orderList.forEach(e->{
                    OrderBook orderBook = orderBookMap.get(e.getId());
                    e.setOrderBook(orderBook);
                });
            }
        }
        return orderList;
    }

    /**
     * 设置订单的流水和商品数据
     * @param orderList
     * @param setShopData
     * @return List<Order>
     */
    private List<Order> setDetailsDataOrShopData(List<Order> orderList ,boolean setShopData){
        if(ObjectUtils.isNotEmpty(orderList)){
            String orderIds = orderList.stream().map(e->e.getId().toString()).distinct().collect(Collectors.joining(","));
            Map<BigDecimal,List<OrderDetails>> detailsListMap = orderDetailsBiz.findOrderDetailsMapByOrderIds(orderIds,false,setShopData,false);
            if(ObjectUtils.isNotEmpty(detailsListMap)){
                orderList.forEach(e->{
                    List<OrderDetails> orderDetailsList = detailsListMap.get(e.getId());
                    e.setOrderDetailsList(orderDetailsList);
                });
            }
        }
        return orderList;
    }

    /**
     * 获取订单的查询条件SQL
     * @param condition 查询条件对象
     * @return SQL
     */
    private String getWhereSql(OrderCondition condition){
        StringBuilder whereSql = new StringBuilder(" 1=1 ");
        if(ObjectUtils.isNotEmpty(condition)){
            if(StringUtils.isNotEmpty(condition.getIds())){
                whereSql .append( " and id in (").append( condition.getIds()).append(")");
            }
            if(StringUtils.isNotEmpty(condition.getKeyword())){
                if(StringUtils.isNotEmpty(condition.getKeyword())){
                    whereSql .append(orderDetailsBiz.getKeywordSql(condition.getKeyword(),condition.getUserIds()));
                }            }
            if(StringUtils.isNotEmpty(condition.getOrderType())){
                whereSql .append(" and orderType = '").append(condition.getOrderType()).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getUserId())){
                whereSql .append(" and userId = ").append(condition.getUserId());
            }
            if(StringUtils.isNotEmpty(condition.getPayType())){
                whereSql .append(" and payType = '").append(condition.getPayType()).append("'");
            }
            if(StringUtils.isNotEmpty(condition.getPayTypeList())){
                whereSql .append(" and payType in (").append(condition.getPayTypeList()).append(")");
            }
            if(StringUtils.isNotEmpty(condition.getOrderStatus())){
                whereSql .append(" and orderStatus='").append(condition.getOrderStatus()).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getSpread())){
                whereSql .append(" and spread = ").append( condition.getSpread());
            }
            if(ObjectUtils.isNotEmpty(condition.getBeginCreateTime())){
                whereSql .append(" and createTime >= '").append( DateUtils.format(condition.getBeginCreateTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getEndCreateTime())){
                whereSql .append(" and createTime <= '").append( DateUtils.format(condition.getEndCreateTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getBeginPayTime())){
                whereSql .append(" and payTime >= '").append( DateUtils.format(condition.getBeginPayTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getEndPayTime())){
                whereSql .append(" and payTime <= '").append( DateUtils.format(condition.getEndPayTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(StringUtils.isNotEmpty(condition.getNotPayType())){
                whereSql .append(" and (payType not in (").append(condition.getNotPayType()).append(") or payType is null)");
            }
            if(StringUtils.isNotEmpty(condition.getSellTypeList())){
                whereSql .append(" and sellTypeList like '%").append(condition.getSellTypeList().trim()).append("%'");
            }
            if(StringUtils.isNotEmpty(condition.getShopNames())){
                whereSql .append(" and shopNames like '%").append(condition.getShopNames().trim()).append("%'");
            }
            if(ObjectUtils.isNotEmpty(condition.getGainDay())){
                whereSql .append(" and createTime >='").append(DateUtils.format(DateUtils.getPastDate(condition.getGainDay()==1?7:30) ,"yyyy-MM-dd")).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getStatus())){
                whereSql .append(" and status=").append(condition.getStatus());
            }
        }
        whereSql .append(" order by createTime desc");
        return whereSql.toString();
    }

    /**
     * 通过订单ID串订单数据
     * @param orderIds 订单ID
     * @return Map<BigDecimal,OrderBook>
     */
    public Map<BigDecimal,Order> findOrderByOrderIds(String orderIds){
        List<Order> orderList = this.find(" id in ("+orderIds+")",null,null);
        if(ObjectUtils.isNotEmpty(orderList)){
            return orderList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
        }
        return null;
    }

    /**
     * 查询交易额度与订单量分布数据列表
     * @return List<Map<String,Object>>
     */
    public List<Map<String,Object>> queryOrderTradeSpreadList(String timeSql){
        return orderDao.queryOrderTradeSpreadList(Order.class,timeSql);
    }

    /**
     * 查询订单支付方式占比统计数据
     * @return PayTypeCountNum
     */
    public PayTypeCountNum queryOrderPayTypeOrderNum(String timeSql){
        PayTypeCountNum payTypeCountNum = orderDao.queryOrderPayTypeOrderNum(Order.class,timeSql);
        if(payTypeCountNum==null){
            payTypeCountNum = new PayTypeCountNum();
        }
        return payTypeCountNum;
    }

    /**
     * 查询订单的支付来源数据统计
     * @return PayOrderFormNum
     */
    public PayOrderFormNum queryPayOrderFormNumData(String timeSql){
        PayOrderFormNum payOrderFormNum = orderDao.queryPayOrderFormNumData(Order.class,timeSql);
        if(payOrderFormNum==null){
            payOrderFormNum = new PayOrderFormNum();
        }
        return payOrderFormNum;
    }

    /**
     * 获取指定时间段内的付款用户量统计数据列表
     * @param type
     * @param timeSql
     * @return List<ZStatisticsOrderBaseCount>
     */
    public List<ZStatisticsOrderBaseCount> queryOrderPayUserCountList(int type,String timeSql){
        Map<String,Object> params = new HashMap<>();
        params.put("type",type);
        params.put("timeSql",timeSql);
        return orderDao.queryOrderPayUserCountList(Order.class,params);
    }

    /**
     * 查询付款用户概况数据
     * @param timeSql 查询时间
     * @return ZStatisticsPayUserCount
     */
    public ZStatisticsPayUserCount queryPayUserCountData(String timeSql){
        return orderDao.queryPayUserCountData(Order.class,timeSql);
    }

    /**
     * 创建订单
     * @param createOrderDataFrom 数据对象
     * @return Order 订单对象
     */
    @Transactional
    public Order createOrder(CreateOrderDataFrom createOrderDataFrom) throws Exception{
        //创建订单对象
        Order order = new Order();
        //设置订单数据
        this.setCreateOrderData(order,createOrderDataFrom);
        //保存订单
        this.save(order);

        //保存图书扩展订单数据
        OrderBook orderBook = order.getOrderBook();
        if(orderBook !=null){
            orderBook.setOrderId(order.getId());
            orderBookBiz.save(orderBook);
        }
        //保存订单的流水记录
        orderDetailsBiz.saveOrderDetails(order,createOrderDataFrom);

        //如果包含有图书，则创建图书订单的扩展数据记录
        if(order.getSellTypeList().contains(ShopType.ORDER_SHOP_BOOK)){
            orderBookBiz.createOrderBook(order);
        }
        //如果使用了优惠券
        if(DataUtil.idIsNotNull(order.getCouponCodeId())){//修改优惠券的状态为已使用
            opCouponCodeBiz.updateOrderUseCodeStatus(order.getCouponCodeId(),5);
        }
        //删除购物车
        if(!StringUtils.isNotEmpty(createOrderDataFrom.getShopData())){
            String shopCartIds = createOrderDataFrom.getShopList().stream().filter(e->StringUtils.isNotEmpty(e.getShopCartId())).map(e->e.getShopCartId().toString()).collect(Collectors.joining(","));
            shopCartBiz.deleteOrderShopCart(shopCartIds);
        }

        //如果是支付成功状态，刚生成各种购买记录
        if(order.getOrderStatus().equals(OrderStatus.SUCCESS)){
            successCallbackHandle.handleSuccess(order);
        }
        return order;
    }

    /**
     * 设置创建订单数据
     * @param order 订单对象
     * @param createOrderDataFrom 订单表单对象
     */
    private void setCreateOrderData(Order order,CreateOrderDataFrom createOrderDataFrom){
        //订单号
        String orderNo = GenerateOrderNum.getInstance().generateOrderNo();
        order.setOrderNo(orderNo);
        //订单类型，COMMON普通订单，ACCOUNT充值订单
        order.setOrderType(createOrderDataFrom.getOrderType());
        //订单的用户ID
        order.setUserId(createOrderDataFrom.getUserId());
        //设置订单价格
        this.setOrderPrice(order,createOrderDataFrom);
        if(order.getRealPrice() <=0&&!createOrderDataFrom.getPayType().equals(PayType.PAY_TYPE_ADMIN_FREE)){//如果价格为0，则直接设置支付成功
            order.setPayType(PayType.PAY_TYPE_FREE);
            order.setPayTime(new Date());
            order.setOrderStatus(OrderStatus.SUCCESS);
        } else if (createOrderDataFrom.getPayType().equals(PayType.PAY_TYPE_ADMIN_FREE)) {
            order.setPayType(PayType.PAY_TYPE_ADMIN_FREE);
            order.setPayTime(new Date());
            order.setOrderStatus(OrderStatus.SUCCESS);
        }else{
            order.setOrderStatus(OrderStatus.INIT);
        }
        //订单来源,WEB，APP，MOBILE
        order.setOrderForm(createOrderDataFrom.getOrderForm());
        //优惠卷id
        if(ObjectUtils.isNotEmpty(createOrderDataFrom.getCouponCode())){
            order.setCouponCodeId(createOrderDataFrom.getCouponCode().getId());
        }
        //活动ID
        order.setActivityId(createOrderDataFrom.getActivityId());

        List<ShopData> shopDataList = createOrderDataFrom.getShopList();

        //商品类型集
        Set<String> shopTypeSet = new HashSet<>();
        shopDataList.stream().forEach(e->shopTypeSet.add(e.getShopType()));
        String sellTypeList = shopTypeSet.stream().collect(Collectors.joining(",",",",","));
        order.setSellTypeList(sellTypeList);
        //购买商品名串
        String shopNames = shopDataList.stream().map(e->e.getShopName()).collect(Collectors.joining(","));
        order.setShopNames(shopNames);
        //状态，1正常，2删除
        order.setStatus(1);

        Map<String,List<ShopData>> shopListMap = shopDataList.stream().collect(Collectors.groupingBy(e->e.getShopType()));
        //图书扩展订单
        List<ShopData> bookShopList = shopListMap.get(ShopType.ORDER_SHOP_BOOK);
        if(ObjectUtils.isNotEmpty(bookShopList)){
            OrderBook orderBook = new OrderBook();
            orderBook.setOrderNo(orderNo);
            orderBook.setUserId(order.getUserId());
            orderBook.setAddress(createOrderDataFrom.getAddress());
            orderBook.setMailStatus(1);
            orderBook.setSignStatus(1);
            order.setOrderBook(orderBook);
        }
        //有推广数据的商品
        List<ShopData> dataList = shopDataList.stream().collect(Collectors.groupingBy(e->StringUtils.isNotEmpty(e.getShareKey()))).get(true);
        //是否是推广订单，0否，1是
        if(ObjectUtils.isNotEmpty(dataList)){
            order.setSpread(1);
        }

    }

    /**
     * 设置订单价格
     * @param order
     * @param createOrderDataFrom
     */
    private void setOrderPrice(Order order,CreateOrderDataFrom createOrderDataFrom){
        OrderPriceHandle.sysConfigBiz = sysConfigBiz;
        //获取订单价格对象
        OrderPrice orderPrice = OrderPriceHandle.getOrderPrice(createOrderDataFrom);
        //订单原价格
        order.setSumPrice(orderPrice.getSumPrice());
        //活动减额
        order.setActivityPrice(orderPrice.getActivityPrice());
        //优惠减金额
        order.setYhPrice(orderPrice.getYhPrice());
        //会员减免金额
        order.setMemberSubPrice(orderPrice.getMemberSubPrice());
        //订单实际价格
        order.setRealPrice(orderPrice.getRealPrice());
        //运费
        order.setFreightPrice(orderPrice.getFreightPrice());
    }
}
